# -*- coding: utf-8 -*-
"""
@author: wyb
@date: 2023/12/5
@time: 21:43
@desc: wdhwyb@hotmail.coma
"""

from imapclient import IMAPClient
from datetime import datetime
import email
from email.header import decode_header

# 邮箱登录信息
email_address = "wdhwyb@hotmail.com"
app_password = "kdmicdbrsbquwpql"  # 应用密码，而不是登录密码

# 连接IMAP服务器
with IMAPClient("outlook.office365.com") as client:
    # 登录邮箱
    client.login(email_address, app_password)

    # 选择收件箱
    client.select_folder("inbox")

    # 定义搜索条件，获取自2023-11-01后来自12306@rails.com.cn的邮件
    search_criteria = [
        'SINCE', datetime(2023, 11, 1),
        'FROM', '49402612@qq.com'
    ]

    # 获取符合搜索条件的邮件 ID 列表
    messages = client.search(search_criteria)

    # 获取并输出邮件内容
    for msg_id, data in client.fetch(messages, ["RFC822"]).items():
        email_message = email.message_from_bytes(data[b"RFC822"])

        # 打印邮件主题
        subject, encoding = decode_header(email_message["Subject"])[0]
        if isinstance(subject, bytes):
            subject = subject.decode(encoding if encoding else "utf-8")
        print("Subject:", subject)

        # 获取邮件正文
        if email_message.is_multipart():
            for part in email_message.walk():
                if part.get_content_type() == "text/plain":
                    body = part.get_payload(decode=True)
                    print("Body:", body.decode("utf-8"))
        else:
            body = email_message.get_payload(decode=True)
            print("Body:", body.decode("utf-8"))

# 注意：使用 IMAPClient 时，with 语句确保在使用后正确关闭连接
